<template>
  <div class="form-view-print flex items-center justify-center"
       id="myPrint">
    <div v-loading="loading"
         class="relative"
         v-if="jsonData.list">
      <fm-generate-form :data="jsonData"
                        :remote="remoteFuncs"
                        :remoteOption="remoteOption"
                        :value="{
                            ...form,
                            material_list:boms,
                          }"
                        ref="generate-form"
                        :class="['preview-form no-print',{
                          'print-hidden-form':isPrint
                        }]">
      </fm-generate-form>
      <fm-generate-form :data="jsonData"
                        :remote="remoteFuncs"
                        :remoteOption="remoteOption"
                        v-for="(value,key) in groupBoms"
                        :key="key"
                        :class="{'print-hidden-form':!isPrint}"
                        :value="{
                            ...form,
                            material_list:value,
                            sdepot_list_value:key
                          }">
      </fm-generate-form>
    </div>
    <div class="form-view-footer no-print"
         v-if="isPrint">

    </div>
  </div>
</template>

<script>
import store from '@/store'
import Cookies from 'js-cookie'
import getDataset from './form-fuction'
import http from '@/utils/request'
import { groupBy, get, cloneDeep } from 'lodash'
export default {
  props: {
    formViewData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rowDataItem: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      dynamicData: {
        radio_options: []
      },
      remoteFuncs: {
        func_options (resolve) {
          getDataset.clientList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        },
        clientList (resolve) {
          getDataset.timeZoneList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        }
      },
      remoteOption: {},

      form: {},
      config: null,
      loading: false,
      printData: null,
      formVersion: undefined,
      isPrint: false
    }
  },
  computed: {
    boms () {
      return get(this.rowDataItem, 'material_list') || []
    },
    sdepotLength () {
      return Object.keys(this.groupBoms).length
    },
    groupBoms () {
      return groupBy(this.boms, 'sdepot_name')
    },
    jsonData () {
      const formSchema = get(this.config, 'data.formSchema') || {}
      return this.apiConfig(formSchema)
    }
  },
  mounted () {
    this.init()
  },

  methods: {
    async init () {
      try {
        this.loading = true
        if (!this.printData) {
          this.printData = JSON.parse(localStorage.getItem('rowData_print'))
        }
        if (this.printData) {
          localStorage.setItem('rowData_print', null)
          if (this.printData.formCode) {
            this.rowDataItem = this.printData
            await this.getData(this.printData.formCode, this.printData.dataFrom)
            setTimeout(() => {
              if(this.$refs['generate-form']&&this.$refs['generate-form'].getComponent){
                  this.$refs['generate-form'].getComponent('print_show').$el.onclick = () => {
                  this.isPrint = true
                  setTimeout(() => {
                    window.print()
                    this.isPrint = false
                    }, 100)
                  }
                }
              })
            }
        }
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    resetFormMaking () {
      this.jsonData = {}
      if (this.$refs.generateForm) {
        this.$refs.generateForm.reset()
      }
      Object.assign(this.$data, this.$options.data())
    },

    async getData (formCode, type) {
      const params = { formCode }
      const { getjsonDataApi, getFormDataApi } = this.$interface.reports
      const { data: response } = await getjsonDataApi(params)
      if (response.code !== 0) {
        return this.$message.error(response.msg)
      }

      this.config = response
      this.formVersion = response.data.formVersion

      if (type === 'rowdata') {
        try {
          if (this.rowDataItem.material_list && typeof this.rowDataItem.material_list ==='string') { this.rowDataItem.material_list = JSON.parse(this.rowDataItem.material_list) }
          if (this.rowDataItem.oppo_list && typeof this.rowDataItem.oppo_list ==='string') { this.rowDataItem.oppo_list = JSON.parse(this.rowDataItem.oppo_list) }
        } catch (error) {
          this.rowDataItem.material_list = []
          this.rowDataItem.oppo_list = []
        }
        this.form = this.rowDataItem
      } else {
        const params = { id: this.rowDataItem[this.formViewData.formKey] }
        const { data: res } = await getFormDataApi(params)
        if (res.code !== 0) {
          this.$emit('closeLoading')
          return this.$message.error(res.msg)
        }
        this.form = res.data.data.dataContent
        this.formVersion = response.data.form.formVersion
        this.$nextTick(() => {
          this.$refs.generateForm.refresh()
        })
      }
    },
    apiConfig (res) {
      const list = get(res, 'config.dataSource') || []
      const result = cloneDeep(res)
      if (list.length) {
        result.config.dataSource = list.map(record => {
          const { url, headers, ...rest } = record
          headers.tenantCode = Cookies.get('tenant_code') || ''
          headers.timezoneOffset = store.state.user.timezoneOffset ? store.state.user.timezoneOffset : ''
          headers.token = Cookies.get('token') || ''

          return {
            ...rest,
            url: !record.url.startsWith('http') ? `${http.options.baseURL}${record.url}` : record.url,
            headers
          }
        })
      }
      return result
    }

  }
}
</script>
<style lang="scss">
@import "@/assets/scss/global.scss";
.form-view-print {
  padding: 10px;
  width: 100%;
  height: 100%;
}

.fm-form {
  .fm-form-item > label {
    font-size: 50px;
  }
  page-break-after: always;
  .print-btn {
    display: inherit;
    .el-button {
      color: #fff;
      background-color: #17b3a3;
      border-color: #17b3a3;
    }
  }
  &.print-hidden-form {
    display: none;
    .print-btn {
      display: none;
    }
  }
  colgroup > col:nth-of-type(2) {
    width:150px !important;
  }
  colgroup > col:nth-of-type(5)  {
    width:70px !important;
  }
  colgroup > col:nth-of-type(6)  {
    width:80px !important;
  }
}
@media print {
  .no-print {
    visibility: hidden;
  }
}
.form-view-footer {
  position: fixed;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 9999;
}
</style>
